/**
 *
 */
package com.eshopkeeper.web.sys;

import com.baomidou.mybatisplus.plugins.Page;
import com.eshopkeeper.core.base.BaseSysController;
import com.eshopkeeper.core.util.Request2ModelUtil;
import com.eshopkeeper.core.util.UploadUtil;
import com.eshopkeeper.core.util.WebUtil;
import com.eshopkeeper.model.sys.SysUser;
import com.eshopkeeper.model.sys.ext.SysMenuBean;
import com.eshopkeeper.service.sys.SysAuthorizeService;
import com.eshopkeeper.service.sys.SysRoleService;
import com.eshopkeeper.service.sys.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author chenshufeng
 * @Description: 用户管理控制器
 * @date 2017年3月7日
 */
@RestController
@Api(value = "用户管理", description = "用户管理")
@RequestMapping(value = "/user", method = RequestMethod.POST)
public class SysUserController extends BaseSysController {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysAuthorizeService authorizeService;

    @Autowired
    private SysRoleService sysRoleService;

//    @Autowired
//    private LdapService ldapService;
//
//    @Autowired
//    private ForumTaskCheckService forumTaskCheckService;

    // 添加用户信息
    @ApiOperation(value = "添加用户信息")
    //@RequiresPermissions("sys.user.add")
    @RequestMapping(value = "/add")
    public Object add(HttpServletRequest request, ModelMap modelMap) throws Exception {
        SysUser sysUser = Request2ModelUtil.covert(SysUser.class, request);
        if (StringUtils.isNotBlank(sysUser.getAvatar()) && !sysUser.getAvatar().contains("/")) {
            String filePath = UploadUtil.getUploadDir(request) + sysUser.getAvatar();
            String avatar = UploadUtil.remove2DFS("sysUser", "user" + sysUser.getId(), filePath).getRemotePath();
            System.out.println("------------------add:" + avatar);
            //String avatar = UploadUtil.remove2Sftp(filePath, "user" + sysUser.getId());
            sysUser.setAvatar(avatar);
        }
        int count=sysUserService.addSysUser(sysUser);

        return setSuccessModelMap(modelMap,count);
    }

    // 修改用户信息
    @ApiOperation(value = "修改用户信息")
    //@RequiresPermissions("sys.user.update")
    @RequestMapping(value = "/update")
    public Object update(HttpServletRequest request, ModelMap modelMap) throws Exception {
        SysUser sysUser = Request2ModelUtil.covert(SysUser.class, request);
        if (StringUtils.isNotBlank(sysUser.getAvatar()) && !sysUser.getAvatar().contains("/")) {
            String filePath = UploadUtil.getUploadDir(request) + sysUser.getAvatar();
            String avatar = UploadUtil.remove2DFS("sysUser", "user" + sysUser.getId(), filePath).getRemotePath();
            System.out.println("------------------update:" + avatar);
            //String avatar = UploadUtil.remove2Sftp(filePath, "user" + sysUser.getId());
            sysUser.setAvatar(avatar);
        }
        sysUserService.updateUserInfo(sysUser);
        return setSuccessModelMap(modelMap);
    }

    // 修改用户头像
    @ApiOperation(value = "修改用户头像")
    //@RequiresPermissions("sys.user.update")
    @RequestMapping(value = "/updateFace")
    public Object updateFace(HttpServletRequest request, ModelMap modelMap) {
        Map<String, Object> params = WebUtil.getParameterMap(request);
//        SysUser sysUser = Request2ModelUtil.covert(SysUser.class, request);
//        if (StringUtils.isNotBlank(sysUser.getAvatar()) && !sysUser.getAvatar().contains("/")) {
//            String filePath = UploadUtil.getUploadDir(request) + sysUser.getAvatar();
//            String avatar = UploadUtil.remove2DFS("sysUser", "user" + sysUser.getId(), filePath).getRemotePath();
//            System.out.println("------------------update:" + avatar);
//            //String avatar = UploadUtil.remove2Sftp(filePath, "user" + sysUser.getId());
//            sysUser.setAvatar(avatar);
//        }
        System.out.println("------------------avatar:" + params.get("avatar"));
        System.out.println("------------------id:" + params.get("id"));
        sysUserService.updateFace(params);
        return setSuccessModelMap(modelMap);
    }

    // 修改密码
    @ApiOperation(value = "修改密码")
    //@RequiresPermissions("sys.user.updatePassword")
    @RequestMapping(value = "/update/password")
    public Object updatePassword(ModelMap modelMap, @RequestParam(value = "id", required = false) Long id,
                                 @RequestParam(value = "originalPassword", required = false) String originalPassword,
                                 @RequestParam(value = "newPassword", required = false) String newPassword,
                                 HttpServletRequest request) {
        if (newPassword != null && originalPassword != null) {
            if (newPassword.equals(originalPassword)) {
                throw new RuntimeException("原始密码和新密码不能一样");
            }
        }
        sysUserService.updatePassword(id, newPassword);
        return setSuccessModelMap(modelMap, "修改成功");
    }

    // 修改密码
    @ApiOperation(value = "修改密码")
    //@RequiresPermissions("sys.user.update")
    @RequestMapping(value = "/update/passwords")
    public Object updatePasswords(ModelMap modelMap, HttpServletRequest request) {
        Map<String, Object> params = WebUtil.getParameterMap(request);
        String newPassword = params.get("newPassword")==null?"":String.valueOf(params.get("newPassword"));
        String originalPassword = params.get("originalPassword")==null?"":String.valueOf(params.get("originalPassword"));
        Map<String,Object> resultmap= new HashMap<>();
        if (!"".equals(newPassword) && !"".equals(originalPassword) ) {
            if (newPassword.equals(originalPassword)) {
                    resultmap.put("state",0);
                    resultmap.put("msg","原始密码和新密码不能一样！");
                    return setSuccessModelMap(modelMap, resultmap);
            }
            Long id = getCurrUser();
            SysUser sysUser = sysUserService.queryById(id);
            if (sysUser != null) {
                if(!sysUser.getPassword().equals(sysUserService.encryptPassword(originalPassword))) {
                    resultmap.put("state",0);
                    resultmap.put("msg","原始密码输入不正确！");
                    return setSuccessModelMap(modelMap, resultmap);
                }
            }
        }

        sysUserService.updatePassword(1L, String.valueOf(params.get("newPassword")));
        resultmap.put("state",1);
        resultmap.put("msg","修改成功");
        return setSuccessModelMap(modelMap, resultmap);
    }


    // 查询用户
    @ApiOperation(value = "查询用户")
    //@RequiresPermissions("sys.user.read")
    @RequestMapping(value = "/read/list")
    public Object get(HttpServletRequest request, ModelMap modelMap) {
        Map<String, Object> params = WebUtil.getParameterMap(request);
        Page<?> list = sysUserService.queryBeans(params);
        return setSuccessModelMap(modelMap, list);
    }

    // 用户详细信息
    @ApiOperation(value = "用户详细信息")
    //@RequiresPermissions("sys.user.read")
    @RequestMapping(value = "/read/detail")
    public Object detail(ModelMap modelMap, @RequestParam(value = "id", required = false) Long id) {
        SysUser sysUser = sysUserService.queryById(id);

        if (sysUser != null) {
            sysUser.setPassword(null);
        }
        return setSuccessModelMap(modelMap, sysUser);
    }

    // 当前用户
    @ApiOperation(value = "当前用户信息")
    @RequestMapping(value = "/read/current")
    public Object current(ModelMap modelMap) {
        Long id = getCurrUser();
        SysUser sysUser = sysUserService.queryById(id);
        if (sysUser != null) {
            sysUser.setPassword(null);
        }
        List<SysMenuBean> menus = authorizeService.queryAuthorizeByUserId(id);
        modelMap.put("user", sysUser);
        modelMap.put("menus", menus);
        
//        logger.info("userType:" + sysUser.getUserType());
//        // userType == 4是慧驿站用户
//        if (4 == sysUser.getUserType()) {
//        	logger.info("userType:" + sysUser.getUserType());
//        	try {
//            	// 如果当前用户是慧驿站用户，则需查询个人任务：已完成任务数、未完成任务数，未完成任务明细（任务名称：帖子title）
//                Map<String, Object> queryMap = new HashMap<String, Object>();
//                queryMap.put("userId", id);
//
//                int finishCount = forumTaskCheckService.getFinishTaskCount(queryMap);
//                modelMap.put("finishCount", finishCount);
//
//                List<ForumTaskCheckBean> beanlist = forumTaskCheckService.getUnFinishTask(queryMap);
//                modelMap.put("unFinishCount", beanlist.size());
//                modelMap.put("beanlist", beanlist);
//
//                // 查询任务池中所有任务（任务名称：帖子title、已分配人员、状态）
//                List<ForumTaskCheckBean> allBeanlist = forumTaskCheckService.getAllFinishTask();
//                modelMap.put("allBeanlist", allBeanlist);
//    		} catch (Exception e) {
//    			e.printStackTrace();
//    		}
//        }

        return setSuccessModelMap(modelMap);
    }

    // 启用禁用
    @ApiOperation(value = "修改状态")
    //@RequiresPermissions("sys.user.disable")
    @RequestMapping(value = "/update/disable")
    public Object disable(ModelMap modelMap, @RequestParam(value = "id", required = false) Long id,
                          @RequestParam(value = "enable", required = false) Integer enable) {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("id", id);
        paramMap.put("enable", enable);
        sysUserService.updateEnable(paramMap);
        return setSuccessModelMap(modelMap);
    }

    // 查询权限角色列表
    @RequestMapping(value = "/selSysRoleList", method = RequestMethod.POST)
    public Object selSysRoleList(HttpServletRequest request, ModelMap modelMap) {
        List<Map<String, Object>> OrizeList = sysRoleService.selSysRoleList();
        return setSuccessModelMap(modelMap, OrizeList);
    }

    // 重置密码
//    @ApiOperation(value = "重置密码")
//    //@RequiresPermissions("sys.user.resetPassword")
//    @RequestMapping(value = "/update/resetPassword")
//    public Object resetPassword(ModelMap modelMap, @RequestParam(value = "id", required = false) Long id) throws Exception {
//        //首先查询ldap中的发件邮箱和密码
//        SystemSetting email = ldapService.getSystemSetting("email");
//        SystemSetting emailPassword = ldapService.getSystemSetting("email_password");
//        //然后根据id重置密码
//        String data = sysUserService.resetPassword(id,email,emailPassword);
//        if ("0".equals(data)){
//            return setSuccessModelMap(modelMap,"0");//成功
//        } else if ("1".equals(data)) {
//            return setSuccessModelMap(modelMap,"1");//没有找到用户
//        } else if ("2".equals(data)){
//            return setSuccessModelMap(modelMap, "2");//重置失败
//        } else {
//            return setSuccessModelMap(modelMap, "3");//用户的email为空
//        }
//    }
    
    @ApiOperation(value = "查询用户下拉列表")
	//@RequiresPermissions("sys.user.read")
	@RequestMapping(value = "/getUserList")
	public Object getUserList(ModelMap modelMap) throws Exception {
		List<Map<String, Object>> userList = sysUserService.getUserList();
		return setSuccessModelMap(modelMap, userList);
	}
    
}
